<template>
  <div class="currentTime-page">
    <div class="left">
      <div class="title">
        <span>设备列表</span>
        <el-select v-model="provinceCode" :loading="$loadingPlugin.getProvinceList" size="mini" popper-class="select-popper" filterable clearable placeholder="全部省份" style="width: 80px;" @change="provinceChange">
          <el-option v-for="item in provinceList" :key="item.orgSN" :value="item.orgSN" :label="item.name" />
        </el-select>
      </div>
      <div class="facility-box">
        <el-row class="content">
          <el-col :span="8">
            <div class="grid-num">100</div>
            <div class="grid-content">设备总数</div>
          </el-col>
          <el-col :span="8">
            <div class="grid-num">10</div>
            <div class="grid-content">在线设备</div>
          </el-col>
          <el-col :span="8">
            <div class="grid-num">90</div>
            <div class="grid-content">离线设备</div>
          </el-col>
        </el-row>
      </div>
      <div class="content">
        <div class="org">
          <device-tree
            ref="deviceTreeRef"
            title="无"
            :tree-data="treeData"
            :loading="$loadingPlugin.getTreeData"
            @currentChange="currentChange"
            @refresh="getTreeData"
          />
        </div>
      </div>
    </div>
    <div class="right">
      <div class="car-info-box">
        <div class="title">车辆信息</div>
        <el-row class="content">
          <el-col :span="8"><div class="grid-content">车牌号：晋A12345</div></el-col>
          <el-col :span="8"><div class="grid-content">终端ID：0101101102221</div></el-col>
          <el-col :span="8"><div class="grid-content">状态：在线/离线</div></el-col>
        </el-row>
        <el-row class="content">
          <el-col :span="8"><div class="grid-content">企业：太原能源科技燃气公司</div></el-col>
          <el-col :span="8"><div class="grid-content">位置时间：2022-09-08 09:12:12</div></el-col>
          <el-col :span="8"><div class="grid-content">速度：12公里/时（东南）</div></el-col>
        </el-row>
        <el-row class="content">
          <el-col :span="8"><div class="grid-content">位置：山西省太原市迎泽区xxx街道110号（112.341232，29.1211）</div></el-col>
          <el-col :span="8"><div class="grid-content" /></el-col>
          <el-col :span="8"><div class="grid-content" /></el-col>
        </el-row>
      </div>
      <div v-if="isOne" class="video-container1">
        <div class="title">
          {{ showControls ? videoList[0].corpName : '' }}
        </div>
        <div v-show="!videoList[0].videoUrl && !videoList[0].tagInfo" class="video">
          点击左侧设备播放视频。
        </div>
        <div v-show="videoList[0].videoUrl && videoList[0].tagInfo" class="video" @click="resetOne">
          {{ videoList[0].tagInfo }}，请点击<span class="hover">重试</span>
        </div>
        <div v-show="videoList[0].videoUrl && !videoList[0].tagInfo" class="video">
          <EasyPlayer
            ref="easyPlayerRef"
            :video-url="videoList[0].videoUrl"
            :loading="videoList[0].isLoading"
            live
            fluent
            stretch
            autoplay
            muted
            @message="message"
            @timeupdate="timeupdate"
          />
        </div>
        <!-- <div v-show="!$loadingPlugin.getTreeData && showControls" class="cloud-control">
          <div class="top">
            <img :src="require('@/assets/up.png')" alt="" @mousedown="cloudControl('up')" @mouseup="mouseup('up')">
          </div>
          <div class="center">
            <img :src="require('@/assets/left.png')" alt="" @mousedown="cloudControl('left')" @mouseup="mouseup('left')">
            <img :src="require('@/assets/middle.png')" alt="" @mousedown="cloudControl('downPic')">
            <img :src="require('@/assets/right.png')" alt="" @mousedown="cloudControl('right')" @mouseup="mouseup('right')">
          </div>
          <div class="bottom">
            <img :src="require('@/assets/down.png')" alt="" @mousedown="cloudControl('down')" @mouseup="mouseup('down')">
          </div>
        </div> -->
      </div>
      <div v-if="!isOne" class="video-container4">
        <div v-for="item in videoList" :key="item.index" class="container" @click="currentContainer(item.index, item)">
          <div class="title">
            {{ item.corpName ? item.corpName : '--' }}
          </div>
          <div class="video" :style="{'border': currentIndex === item.index ? '1px solid #14ff00' : ''}">
            <div v-show="!item.videoUrl && !item.tagInfo" class="text-container">
              <div class="add-img" />
              <p style="margin-bottom: 10px;">暂未连接设备</p>
              <p>请选择左侧"设备列表"中的设备进行连接</p>
            </div>
            <div v-show="item.videoUrl && item.tagInfo" class="text-container" @click="resetVideo(item.index, item)">
              {{ item.tagInfo }}，请点击<span class="hover">重试</span>
            </div>
            <div v-show="item.videoUrl && !item.tagInfo" class="video-block">
              <EasyPlayer
                :video-url="item.videoUrl"
                :loading="item.isLoading"
                fluent
                live
                stretch
                autoplay
                muted
                @message="message($event ,item.index)"
                @timeupdate="timeupdate($event, item.index)"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="check-container">
        <div v-if="showControls" class="one" title="单屏">
          <i :style="{'opacity': isOne ? '1' : '0.4'}" @click="toggerView(true)" />
        </div>
        <div v-if="showControls" class="four" title="四屏" :style="{'opacity': !isOne ? '1' : '0.4'}">
          <i class="el-icon-menu" @click="toggerView(false)" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
//   import { corpAllList, queryDeviceList, getCorporationInfo, organizationQueryList } from '@/api'
//   import getTreeData from '@/utils/jsonTree'
//   import { setDeveceChildren } from '@/utils'
  import EasyPlayer from '@easydarwin/easyplayer'
  import axios from 'axios'

  export default {
    name: 'playLive',
    components: {
      deviceTree: require('./deviceTree.vue').default,
      EasyPlayer
    },
    data() {
      return {
        delayTime: null,
        provinceCode: '',
        provinceList: [],
        currentBoxInfo: null,
        currentIndex: 1,
        isOne: true,
        deviceList: [],
        currentDevece: null,
        videoList: [
          {
            index: 1,
            corpName: '--',
            videoUrl: '',
            tagInfo: '',
            id: undefined,
            isLoading: false
          },
          {
            index: 2,
            corpName: '--',
            videoUrl: '',
            tagInfo: '',
            id: undefined,
            isLoading: false
          },
          {
            index: 3,
            corpName: '--',
            videoUrl: '',
            tagInfo: '',
            id: undefined,
            isLoading: false
          },
          {
            index: 4,
            corpName: '--',
            videoUrl: '',
            tagInfo: '',
            id: undefined,
            isLoading: false
          }
        ],
        treeData: [],
        showControls: true
      }
    },
    async created() {
    //   this.getProvinceList()
    //   this.getCorporationInfo()
    //   await this.getTreeData()
    //   this.getFirstDevice()
    },
    methods: {
      // 获取企业列表
      async getCorporationInfo() {
        // const res = await getCorporationInfo()
        // console.log(res)
      },
      useDelay() {
        if (this.delayTime) {
          clearInterval(this.delayTime)
        }
        this.delayTime = setInterval(() => {
          if (this.getId('video') && this.getId('video').src) {
            const buffered1 = this.getId('video').buffered
            if (buffered1.length > 0) {
              // 缓冲区末尾时间
              const end = buffered1.end(0)
              // diff是缓冲区末尾时间和当前播放时间的差值
              const diff = end - this.getId('video').currentTime
              // 如果差值大于1，说明延迟大于1s，需要手动跳帧
              if (diff > 1) {
                // 将当前播放时间设置为缓冲区末尾时间减一的这个时间点
                this.getId('video').currentTime = end - 1
              }
            }
          }
        }, 20000)
      },
      getId(id) {
        return document.querySelector(id)
      },
      resetVideo(index, item) {
        const url = this.videoList[index - 1].videoUrl
        this.videoList[index - 1].videoUrl = ''
        this.videoList[index - 1].tagInfo = ''
        setTimeout(() => {
          this.videoList[index - 1].videoUrl = url
        }, 100)
      },
      resetOne() {
        this.videoList[0].videoUrl = ''
        setTimeout(() => {
          this.currentChange(this.currentDevece)
        }, 100)
      },
      getFirstDevice() {
        const arr = []
        this.treeData.forEach(item => {
          findFirstDevice(item)
        })
        function findFirstDevice(row) {
          if (row.children && row.children.length) {
            row.children.forEach(item => {
              findFirstDevice(item)
              if (item.isVideo) {
                arr.push(item)
              }
            })
          }
        }
        if (arr.every(item => !item.isOnline)) {
          this.videoList[0].tagInfo = '未连接到设备'
          this.showControls = false
          return
        } else {
          this.showControls = true
        }
        this.videoList[0].videoUrl = arr.filter(item => item.isOnline)[0].url.slice(0, -4) + '/hls.m3u8'
        this.videoList[0].corpName = arr.filter(item => item.isOnline)[0].allName
      },
      timeupdate(time, index) {
        if (this.isOne) {
          if (time) this.videoList[0].isLoading = false
        } else {
          if (time) this.videoList[index - 1].isLoading = false
        }
      },
      message(err, index) {
        if (err.type === 'error') {
          if (this.isOne) {
            this.videoList[0].tagInfo = err.message || '视频加载失败，请刷新后重试'
          } else {
            this.videoList[index - 1].tagInfo = err.message || '视频加载失败，请刷新后重试'
          }
        }
      },
      async getProvinceList() {
        // const res = await organizationQueryList({
        //   orgType: 2,
        //   useStatus: 0 // -1查询所有，0查询已启用
        // })
        // this.provinceList = res.data
      },
      // 云台控制,鼠标按下
      cloudControl(direction) {
        if (direction === 'downPic') return document.querySelector('.icon-picture').click()
        const params = {
          StartStop: 1,
          Speed: 5
        }
        switch (direction) {
        case 'up': {
          params.PTZCmd = 1
          break
        }
        case 'left': {
          params.PTZCmd = 3
          break
        }
        case 'right': {
          params.PTZCmd = 4
          break
        }
        case 'down': {
          params.PTZCmd = 2
          break
        }
        }
        axios.get(this.currentDevece.camPtzAddress, { params })
      },
      // 鼠标离开
      mouseup(direction) {
        const params = {
          StartStop: 0,
          Speed: 5
        }
        switch (direction) {
        case 'up': {
          params.PTZCmd = 1
          break
        }
        case 'left': {
          params.PTZCmd = 3
          break
        }
        case 'right': {
          params.PTZCmd = 4
          break
        }
        case 'down': {
          params.PTZCmd = 2
          break
        }
        }
        axios.get(this.currentDevece.camPtzAddress, { params })
      },
      // 切换单屏四屏
      toggerView(flag) {
        if (!flag) this.currentIndex = 1
        this.videoList.forEach(item => {
          item.corpName = '--'
          item.videoUrl = ''
          item.tagInfo = ''
          item.isLoading = false
        })
        this.isOne = flag
        this.$refs.deviceTreeRef.$refs.tree.setCurrentKey(this.treeData[0].id)
        if (flag) {
          if (!this.currentBoxInfo) return
          this.videoList[0].corpName = this.currentBoxInfo.corpName
          this.videoList[0].videoUrl = this.currentBoxInfo.videoUrl
          this.videoList[0].tagInfo = this.currentBoxInfo.tagInfo
          this.videoList[0].isLoading = this.currentBoxInfo.isLoading
          this.$refs.deviceTreeRef.$refs.tree.setCurrentKey(this.currentBoxInfo.id)
          this.currentBoxInfo = null
        }
      },
      // 四屏下选中的容器
      currentContainer(index, item) {
        this.currentIndex = index
        if (!item.videoUrl) return
        this.currentBoxInfo = JSON.parse(JSON.stringify(item))
      },
      // 选中设备
      currentChange(val) {
        if (!val.isVideo) return
        if (!val.isOnline) return this.$message.error('当前设备不在线')
        this.useDelay()
        this.currentDevece = val
        if (this.isOne) {
          this.videoList[0].corpName = val.allName
          this.videoList[0].videoUrl = val.url.slice(0, -4) + '/hls.m3u8'
          this.videoList[0].tagInfo = ''
          this.videoList[0].isLoading = true
          this.videoList[0].id = val.id
        } else {
          this.videoList[this.currentIndex - 1].corpName = val.allName
          this.videoList[this.currentIndex - 1].videoUrl = val.url.slice(0, -4) + '/hls.m3u8'
          this.videoList[this.currentIndex - 1].tagInfo = ''
          this.videoList[this.currentIndex - 1].isLoading = true
          this.videoList[this.currentIndex - 1].id = val.id
          if (this.currentIndex === 4) return
          this.currentIndex++
        }
      },
      // 获取机构树
      async getTreeData(orgSN) {
        // const [res, res1] = await Promise.all([corpAllList({ orgSN: orgSN || '' }), queryDeviceList({ currentPage: 1, pageSize: 99999 })])
        // const data = res.data.map(item => ({
        //   label: item.name,
        //   id: item.id,
        //   ...item
        // }))
        // // 对返回的res1数据进行处理 orgId deveceName isVideo isOnline url
        // this.deviceList = res1.data.rows.map(item => {
        //   return {
        //     ...item,
        //     isVideo: item.deviceNo,
        //     isOnline: item.deviceStatus,
        //     url: item.liveAddress
        //   }
        // })
        // const newData = setDeveceChildren(data, this.deviceList)
        // this.treeData = getTreeData(newData, 'parentId', 'id')
      },
      // 切换省份
      async provinceChange(value) {
        await this.getTreeData(value)
        this.getFirstDevice()
      }
    }
  }
</script>

<style lang="scss" scoped>
.hover {
  color: #1976D2;
  &:hover {
    color: aqua;
  }
}
.currentTime-page {
  display: flex;
  height: calc(100vh - 150px);
  padding: 16px;
  padding: 10px 10px 0 10px;
  margin: 6px 8px;
  cursor: pointer;
  .left {
    width: 260px;
    margin-right: 16px;
    font-size: 14px;
    background: #fff;
    border: 1px solid #DCDFE6;
    border-radius: 6px;
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 40px;
      padding: 8px;
      background: #fff;
      border-radius: 6px 6px 0 0;
      /deep/ .el-select .el-input__inner {
        padding: 0;
        background-color: transparent;
        border-color: transparent;
      }
    }
    .facility-box {
      text-align: center;
      border-bottom: 1px solid #DCDFE6;
      .grid-num {
        margin-bottom: 5px;
        font-size: 18px;
        font-weight: 600;
      }
    }
    .content {
      height: calc(100% - 98px);
      padding: 8px;
      .search {
        /deep/ .el-input__inner {
          background-color: #fff;
          border-color: transparent;
          border-radius: 50px;
        }
      }
      .org {
        height: calc(100% - 102px);
        margin-top: 12px;
        /deep/ .el-tree {
          background-color: transparent;
        }
      }
    }
  }
  .right {
    width: calc(100% - 276px);
    height: 100%;
    overflow-x: auto;
    .car-info-box {
      padding: 10px;
      margin-bottom: 10px;
      background: #fff;
      border: 1px solid #DCDFE6;
      border-radius: 6px;
      .title {
        font-weight: 600;
      }
      .content {
        margin-top: 5px;
        font-size: 14px;
        // div{
        //   width: 33%;
        //   text-overflow: ellipsis;
        //   white-space: nowrap;
        // }
      }
    }
    .video-container1 {
      position: relative;
      width: 100%;
      height: calc(100% - 188px);
      //min-width: 1200px;
      .title {
        height: 40px;
        padding: 0 16px;
        line-height: 40px;
        background: #fff;
        border: 1px solid #DCDFE6;
        border-radius: 6px 6px 0 0;
      }
      .video {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: calc(100% - 40px);
        font-size: 18px;
        color: #AFBDD1;
        background-color: #000;
        user-select: none;
      }
      .cloud-control {
        position: absolute;
        bottom: 48px;
        left: 28px;
        display: flex;
        flex-direction: column;
        width: 170px;
        height: 170px;
        .top,
        .center,
        .bottom {
          display: flex;
          justify-content: center;
          flex: 1;
          & > img {
            cursor: pointer;
            opacity: 0.7;
            &:hover {
              opacity: 1;
            }
          }
        }
        .center {
          justify-content: space-between;
        }
      }
    }
    .video-container4 {
      display: flex;
      //min-width: 1200px;
      flex-wrap: wrap;
      width: 100%;
      //height: 100%;
      height: calc(100% - 188px);
      .container {
        display: flex;
        flex-direction: column;
        width: 50%;
        height: 50%;
        .title {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 40px;
          padding: 8px;
          background: #fff;
          border: 1px solid #DCDFE6;
          border-radius: 6px 6px 0 0;
        }
        .video {
          position: relative;
          width: 100%;
          //height: 355px;
          height: 100%;
          padding-bottom: 5px;
          font-size: 18px;
          color: #AFBDD1;
          background-color: #000;
          border: 1px solid #DCDFE6;
          user-select: none;
          .text-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            .add-img {
              width: 48px;
              height: 48px;
              margin-bottom: 20px;
              background: url('~@/assets/add-img.png') no-repeat;
            }
          }
          .video-block {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100% !important;
          }
        }
      }
    }
    .check-container {
      width: 100%;
      height: 74px;
      //min-width: 1200px;
      padding: 10px;
      background-color: #fff;
      border: 1px solid #DCDFE6;
      border-radius: 0 0 6px 6px;
      .one {
        display: inline-block;
        width: 30px;
        height: 30px;
        padding: 7px 0 0 7px;
        margin-right: 16px;
        i {
          display: inline-block;
          width: 100%;
          height: 100%;
          cursor: pointer;
          background-color: #9dbbe5;
          border-radius: 2px;
          opacity: 0.8;
          &:hover {
            opacity: 1;
          }
        }
      }
      .four {
        display: inline-block;
        font-size: 30px;
        color: #9dbbe5;
        cursor: pointer;
        opacity: 0.8;
        &:hover {
          opacity: 1;
        }
      }
    }
  }
}
</style>
